﻿using Newtonsoft.Json;
using ShareRss.Dll;
using ShareRss.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ThunderAgentLib;

namespace ShareRss
{
    public partial class MainWindow : Form
    {
        public static MainWindow mainwindow;
        public static string tB_LogoutName;
        public static XmlModel backxmlmodel;
        public static MainModel backmainmodel;
        private bool isVipLink = bool.Parse(ConfigDll.GetConfigValue("isVipLink"));
        public MainWindow()
        {
            InitializeComponent();
            mainwindow = this;
        }

        #region 加载刷新追番列表
        private void MainWindow_Load(object sender, EventArgs e)
        {
            ReadLoveList();
            VipLink.Enabled = false;
            Magnet.Enabled = false;
            Magnet2.Enabled = false;
            Lookshare.Enabled = false;
        }
        public void ReadLoveList()
        {
            var dt = ConfigDll.ReadConfigToDT();
            LoveList.DataSource = dt;
            LoveList.DisplayMember = "Key";
            LoveList.ValueMember = "Value";
            if (dt == null || dt.Rows.Count == 0)
            {
                label1.Text = $"你还没有追番";
            }
            else
            {
                label1.Text = $"当前追番共{dt.Rows.Count}部，点击刷新";
            }

        }
        private void label1_Click(object sender, EventArgs e)
        {
            ReadLoveList();
        }
        private void RemoveAnimation_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定取消吗？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK && LoveList.SelectedValue != null)
            {
                var info = LoveList.SelectedValue.ToString().Replace("|", "_");
                //删除下载好的列表
                TxtIO.Delete($"LoveList/{info}.txt");
                //清空当前列表
                ListName.DataSource = null;
                var configText = ConfigDll.GetConfigValue("LoveList").ToString().Split('@').ToList();
                configText.Remove(info);
                string newListtext = string.Join("@", configText.ToArray());
                ConfigDll.SetConfigValue("LoveList", newListtext);
                ReadLoveList();
            }
        }
        /// <summary>
        /// 添加追番
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            ChangeConfig f2 = new ChangeConfig();
            f2.ShowDialog();
        }
        #endregion
        #region 加载选中番剧的全部列表
        private void ReList_Click(object sender, EventArgs e)
        {
            RefreshList(true);
        }
        private void LoveList_Click(object sender, EventArgs e)
        {
            LoadListName();
        }
        //在list上移动加载
        private void LoveList_KeyUp(object sender, KeyEventArgs e)
        {
            LoadListName();
        }
        public void LoadListName()
        {
            var info = LoveList.SelectedValue;
            if (info != null)
            {
                MainModel model = new MainModel()
                {
                    Name = info.ToString().Split('|')[1],
                    Subtitle = info.ToString().Split('|')[0]
                };
                backmainmodel = model;
                XmlModel infoList = new XmlModel()
                {
                    Item = JsonConvert.DeserializeObject<List<Item>>(TxtIO.Read($"{model.Subtitle}_{model.Name}", "LoveList"))
                };
                if (infoList.Item == null)
                {
                    if (!BackgroundReadRss.IsBusy)
                        BackgroundReadRss.RunWorkerAsync();
                    else
                        MessageBox.Show("正在后台更新，请稍后");
                }
                else
                {
                    backxmlmodel = infoList;
                    ListNameLoadRss();
                }

            }
        }
        private void BackgroundReadRss_DoWork(object sender, DoWorkEventArgs e)
        {
            if (BackgroundReadRss.CancellationPending)
            {
                e.Cancel = true;
            }
            backxmlmodel = ReadRss.AddCondition(backmainmodel);
        }

        private void BackgroundReadRss_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ListNameLoadRss();
        }

        private void ListNameLoadRss()
        {
            DataGridViewCheckBoxColumn checkbox = new DataGridViewCheckBoxColumn()
            {
                Name = "CheckBoxRow",
                HeaderText = "多选",
                Width = 50,
                TrueValue = true,
                FalseValue = false
            };
            if (ListName.Columns.Count != 0)
                ListName.Columns.Remove(ListName.Columns[0]);
            ListName.DataSource = backxmlmodel.Item;
            ListName.Columns[0].HeaderText = "名称";
            ListName.Columns[0].Width = 300;
            ListName.Columns[2].HeaderText = "更新时间";
            ListName.Columns[2].Width = 130;
            ListName.Columns[2].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            ListName.Columns[7].HeaderText = "类别";
            ListName.Columns[7].Width = 60;
            ListName.Columns[1].Visible = false;
            ListName.Columns[3].Visible = false;
            ListName.Columns[4].Visible = false;
            ListName.Columns[5].Visible = false;
            ListName.Columns[6].Visible = false;
            ListName.Columns.Insert(0, checkbox);
            for (var i = 0; i < this.ListName.RowCount; i++)
            {
                this.ListName.Rows[i].Cells[0].Value = false;
            }
            TxtIO.Write(JsonConvert.SerializeObject(backxmlmodel.Item), $"{backmainmodel.Subtitle}_{backmainmodel.Name}", "LoveList");
            label2.Text = $"查询到{ConfigDll.PairSubtitleGroup(int.Parse(backmainmodel.Subtitle))}的{backmainmodel.Name}一共有{backxmlmodel.Item.Count}条数据";
        }
        #endregion
        #region 跟随光标刷新浏览器数据
        private void ListName_CellClick(object sender, DataGridViewCellEventArgs e)
        {

            GridViewCheck(e);
            //判断是否为多选
            List<DataGridViewRow> datalist = new List<DataGridViewRow>();
            for (int i = 0; i < ListName.Rows.Count - 1; i++)
            {
                if (bool.Parse(ListName.Rows[i].Cells[0].Value.ToString()))
                {
                    datalist.Add(ListName.Rows[i]);
                }
            }
            if (datalist.Count > 1)
            {
                //多选
                LoadOtherwebBrowser(datalist);
            }
            else
            {
                //单选
                LoadOnewebBrowser();
            }
        }

        /// <summary>
        /// 展示列表前面的多选勾
        /// </summary>
        /// <param name="e"></param>
        private void GridViewCheck(DataGridViewCellEventArgs e)
        {
            //点击单独的行
            if (e.RowIndex >= 0 && e.ColumnIndex == 0)
            {
                if (bool.Parse(this.ListName.Rows[e.RowIndex].Cells[0].Value.ToString()))
                {
                    this.ListName.Rows[e.RowIndex].Cells[0].Value = false;
                }
                else
                {
                    this.ListName.Rows[e.RowIndex].Cells[0].Value = true;
                }
            }
        }

        private void ListName_KeyUp(object sender, KeyEventArgs e)
        {
            LoadOnewebBrowser();
        }
        private void ListName_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            //try
            //{
            //    var info = ListName.Rows[ListName.CurrentRow.Index + 1];
            //    webBrowser1.Navigate("about:blank");
            //    while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
            //    {
            //        Application.DoEvents();
            //    }
            //    webBrowser1.Document.Write(info.Cells["Description"].Value.ToString());
            //}
            //catch (Exception)
            //{

            //    throw;
            //}
        }

        /// <summary>
        /// 单选
        /// </summary>
        private void LoadOnewebBrowser()
        {
            Browserinfo.Text = $"正在浏览第{(ListName.CurrentCell.RowIndex + 1).ToString()}条";
            DataGridViewRow info = ListName.Rows[ListName.CurrentCell.RowIndex];
            webBrowser1.Navigate("about:blank");
            while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            var html = $"<body><style type='text/css'>img {{width:100%!important;height:auto!important}}</style>{info.Cells["Description"].Value.ToString()}</body>";
            webBrowser1.Document.Write(html);
            BatchdownloadPanel.Visible = false;
            if (isVipLink)
            {
                Lookshare.Enabled = true;
                VipLink.Enabled = true;
                Magnet.Enabled = true;
                Magnet2.Enabled = true;
                MagnetLink urlLink = HtmlToXpath.HtmlToLink(HtmlToXpath.WebParities(info.Cells["Link"].Value.ToString().Trim()));
                urlLink.ShareLink = info.Cells["Link"].Value.ToString().Trim();
                DownLinkTextbox.Text = $"{urlLink.VipLink}@{urlLink.Magnet}@{urlLink.Magnet2}@{urlLink.ShareLink}";
            }
        }

        /// <summary>
        /// 多选
        /// </summary>
        private void LoadOtherwebBrowser(List<DataGridViewRow> datalist)
        {
            int count = datalist.Count;
            Browserinfo.Text = $"已选择{count.ToString()}条";
            if (count > 10)
            {
                MessageBox.Show("受制于迅雷，最多只能同时下载10条");
                Batchdownload.Enabled = false;
            }
            else
            {
                Batchdownload.Enabled = true;
                List<string> downLink = new List<string>();
                for (int i = 0; i < count; i++)
                {
                    downLink.Add(datalist[i].Cells["Enclosure"].Value.ToString());
                }
                BatchdownloadPanel.Visible = true;
                DownLinkTextbox.Text = string.Join("@", downLink.ToArray());
            }

        }
        #endregion
        #region 加载下载和访问
        private void Magnet2_Click(object sender, EventArgs e)
        {
            Thunder(DownLinkTextbox.Text.Split('@')[2]);
        }
        private void VipLink_Click(object sender, EventArgs e)
        {
            var url = DownLinkTextbox.Text.Split('@')[0];
            webBrowser2.Url = new Uri(url);
        }

        private void Magnet_Click(object sender, EventArgs e)
        {
            Thunder(DownLinkTextbox.Text.Split('@')[1]);
        }
        private void Lookshare_Click(object sender, EventArgs e)
        {
            var url = DownLinkTextbox.Text.Split('@')[3];
            System.Diagnostics.Process.Start(url);
        }
        private void Batchdownload_Click(object sender, EventArgs e)
        {
            List<string> list = DownLinkTextbox.Text.Split('@').ToList();
            foreach (var item in list)
            {
                Thunder(item);
            }
        }
        #endregion
        #region 退出确认
        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result = MessageBox.Show("确定退出吗？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                Application.ExitThread();
            }
            else
            {
                e.Cancel = true;
            }
        }
        #endregion
        #region 最小化托盘
        private void MainWindow_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
            }
        }
        #endregion
        #region 监视查看全部更新
        private void ReadRssTime_Tick(object sender, EventArgs e)
        {
            RefreshList();
            //notify("12345", "12345", ToolTipIcon.Error);
        }


        private void button2_Click(object sender, EventArgs e)
        {
            Infos f2 = new Infos();
            f2.ShowDialog();
        }
        #endregion
        #region 方法汇总
        /// <summary>
        /// 弹出气泡
        /// </summary>
        /// <param name="txt"></param>
        public void notify(string title, string txt, ToolTipIcon icon)
        {
            notifyIcon1.ShowBalloonTip(5000, title, txt, icon);
        }

        /// <summary>
        /// 迅雷下载
        /// </summary>
        /// <param name="url"></param>
        private static void Thunder(string url)
        {
            try
            {
                AgentClass agent = new AgentClass();
                //AddTask("下载地址", "另存文件名", "保存目录", "任务注释", "引用地址", "开始模式", "只从原始地址下载", "从原始地址下载线程数") 。 
                agent.AddTask(url, "index", "C://", "", "", -1, 0, 5);
                agent.CommitTasks2(1);//提交
            }
            catch (Exception)
            {
                MessageBox.Show("电脑中没有发现迅雷,请直接下载种子");
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isTime">是否为强制刷新，false为否</param>
        /// <returns></returns>
        public static int RefreshList(bool isTime = false)
        {
            var AllnewList = new List<Item>();
            var dt = ConfigDll.ReadConfigToDT();
            if (dt == null) { return 0; }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                MainModel model = new MainModel()
                {
                    Name = dt.Rows[i]["Value"].ToString().Split('|')[1],
                    Subtitle = dt.Rows[i]["Value"].ToString().Split('|')[0]
                };
                List<Item> newList = ReadRss.AddCondition(model).Item;
                var oldList = JsonConvert.DeserializeObject<List<Item>>(TxtIO.Read($"{model.Subtitle}_{model.Name}", "LoveList"));
                var exceptList = new List<Item>();
                //比较oldList和infoList.Item 取loflist最新的值与infolist比较
                var newListtxt = JsonConvert.SerializeObject(newList);
                for (int x = 0; x < newList.Count; x++)
                {
                    if (oldList != null && oldList.Count > 0 && newList[x].Guid == oldList[0].Guid && newList[x].PubDate == oldList[0].PubDate)
                    {
                        break;
                    }
                    exceptList.Add(newList[x]);
                }
                TxtIO.Write(newListtxt, $"{model.Subtitle}_{model.Name}", "LoveList");
                AllnewList.AddRange(exceptList);
            }
            if (AllnewList.Count > 0)
            {
                TxtIO.Write(JsonConvert.SerializeObject(AllnewList), $"This_Update_List", "LoveList");
                if (AllnewList.Count == 1)
                {
                    mainwindow.notify("更新提示", $"{AllnewList[0].Title}更新了，快去看看吧！", ToolTipIcon.Info);
                }
                else
                {
                    mainwindow.notify("更新提示", $"本次共更新了{AllnewList.Count}部动漫，已经记录到列表内，在主界面点击“查看上次更新”查看", ToolTipIcon.Info);
                }
                return AllnewList.Count;
            }
            if (isTime)
            {
                mainwindow.notify("提示", $"本次没有更新的动漫", ToolTipIcon.Info);
            }
            return 0;
        }


        #endregion
        #region 右键菜单
        private void 强制刷新全部番剧ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshList(true);
        }
        private void 其他设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingForm f2 = new SettingForm();
            f2.ShowDialog();
        }
        private void 退出程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mainwindow.Close();
        }

        private void 查看最近一次更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button2_Click(sender, e);
        }


        #endregion



    }
}
